/**
 * Created by sky on 2019/3/12.
 */
layui.define(function (exports) {
    var NewProtobuf = window.protobuf;

    function CommonProtoBuf3(pbFile, res, msgObj) {
        var self = this;
        self.pbFile = pbFile;
        self.msgObj = msgObj;
        NewProtobuf.load(pbFile, res, function (err, root) {
            if (err) throw err;
            self.root = root;
        });
    }

    CommonProtoBuf3.prototype.getMsgIndex = function (protobufData) {
        var dv = new DataView(protobufData);
        var index = dv.getUint16(0, false);
        return index;
    };

    CommonProtoBuf3.prototype.decode = function (protobufData) {
        var self = this;
        var buffer = new Uint8Array(protobufData);
        var index = self.getMsgIndex(protobufData);
        var msgType = self.msgObj[index];

        var wsMessage;
        if (self.root != null) {
            wsMessage = self.root.lookup(msgType);
            if (!Uint8Array.prototype.slice) {
                Object.defineProperty(Uint8Array.prototype, 'slice', {
                    value: Array.prototype.slice
                });
            }
            var msgDec = wsMessage.decode(buffer.slice(2));
            var msgData = wsMessage.toObject(msgDec, {
                defaults: true,
                enums: String
            });
            return {
                index: index,
                msgData: msgData
            };
        }
    };

    CommonProtoBuf3.prototype.encode = function (sendId, msgType, data) {
        var self = this;
        if (self.root != null) {
            var msg = self.root.lookup(msgType);
            var reason = msg.verify(data);
            if (reason !== null)
                console.log("message is invalid when calling just encode because: " + reason);
            var buffer = msg.encode(data).finish();
            console.log("send data:" + JSON.stringify(data));
            var totalBuffer = new Uint8Array(2 + buffer.byteLength);
            var indexBuffer = new ArrayBuffer(2);
            var dv = new DataView(indexBuffer);
            dv.setUint16(0, sendId, false);
            totalBuffer.set(new Uint8Array(indexBuffer), 0);
            totalBuffer.set(new Uint8Array(buffer), 2);
            return totalBuffer;
        }
    };

    exports('CommonProtoBuf3', CommonProtoBuf3);
});


